package com.rslai.base.tool.servertest.command;

import com.rslai.base.tool.servertest.context.Context;
import com.rslai.base.tool.servertest.database.DbUnitWrapper;
import com.rslai.base.tool.servertest.exception.ExecuteException;
import com.rslai.base.tool.servertest.model.KeyValueStore;
import com.rslai.base.tool.servertest.response.Response;
import com.rslai.base.tool.servertest.util.CloneUtil;
import com.rslai.base.tool.servertest.util.KeyValueUtil;
import com.rslai.base.tool.servertest.util.PropertyUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;

public class PreDataStepCommand extends ParameterizedCommand {
    String file;
    String database;
    String replaceStr;
    String cached;

    public PreDataStepCommand(List<KeyValueStore> params) {
        super(params);
    }

    protected Response doExecuteInternal(Response preResult, List<KeyValueStore> processedParams, Context context) throws Throwable {
        this.file = KeyValueUtil.getValueByKey("file", processedParams);
        this.database = KeyValueUtil.getValueByKey("database", processedParams);
        this.replaceStr = KeyValueUtil.getValueByKey("replaceTableName", processedParams);
        this.cached = KeyValueUtil.getValueByKey("cached", processedParams);

        String globalCached = PropertyUtils.getProperty("cached", "false");
        boolean actualCached = getActualCached(globalCached, this.cached);
        DbUnitWrapper dbUnitWrapper = null;
        try {
            if (StringUtils.isBlank(this.file)) {
                this.logger.info("prepare data command, file is blank");
                return preResult;
            }
            String[] files = this.file.split(",");
            this.logger.info("prepare data command<file={}> is starting...", this.file);
            dbUnitWrapper = new DbUnitWrapper(this.database);
            for (String file : files) {
                if (StringUtils.isNotBlank(file)) {
                    dbUnitWrapper.prepareData(file, this.replaceStr, actualCached);
                }
            }
            return preResult;
        } catch (Exception e) {
            String message = String.format("prepare data step command invoke error, database=<%s>,file=<%s>", new Object[]{this.database, this.file});
            this.logger.error(message, e);
            throw new ExecuteException(message, e);
        }
    }

    public StepCommand doClone() {
        return new PreDataStepCommand(CloneUtil.cloneKeyValueStore(this.params));
    }

    public Map<String, Object> toReport() {
        Map details = new HashMap();
        details.put("stepName", "准备数据:");
        if (StringUtils.isNotEmpty(this.file)) {
            StringBuilder sb = new StringBuilder();
            sb.append("数据库:").append(this.database).append(",");
            sb.append("数据文件：").append("<a href=\"\" onclick=\"return showData.call(this);\">").append(this.file).append("</a>");
            if ((this.replaceStr != null) && (this.replaceStr.split("->").length == 2)) {
                sb.append(", 表名替换：").append(this.replaceStr);
            }
            details.put("name", sb.toString());
        }
        List params = new ArrayList();
        details.put("params", params);
        return details;
    }

    private boolean getActualCached(String globalCached, String cached) {
        if (StringUtils.isNotBlank(cached)) {
            return Boolean.valueOf(cached).booleanValue();
        }
        if (Boolean.valueOf(globalCached).booleanValue()) {
            return true;
        }
        return false;
    }
}
